package com.niodata.dp.core.resource.impl;

import com.niodata.dp.core.resource.Resource;
import com.niodata.dp.core.resource.ResourceType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ResourceGroup<T extends Resource> implements Resource {

  private final List<T> resources;

  private ResourceGroup(List<T> resources) {
    this.resources = Collections.unmodifiableList(resources);
  }

  public static <T extends Resource> ResourceGroupBuilder<T> put(T t) {
    return new ResourceGroupBuilder<T>().put(t);
  }

  public List<T> resources() {
    return resources;
  }

  @Override
  public ResourceType resourceType() {
    return resources.get(0).resourceType();
  }

  @Override
  public String content() {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i != resources.size(); ++i) {
      if (i != 0) {
        sb.append(";");
      }
      sb.append(resources.get(i).content());
    }
    return sb.toString();
  }

  @Override
  public String format() {
    return resourceType().protocol() + "://" + content();
  }

  public static class ResourceGroupBuilder<T extends Resource> {

    private final List<T> cache = new ArrayList<>();

    private ResourceGroupBuilder() {

    }

    public ResourceGroupBuilder<T> put(T t) {
      cache.add(t);
      return this;
    }

    public ResourceGroup<T> build() {
      return new ResourceGroup<>(cache);
    }
  }
}
